package io.renren.modules.bonus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RenException;
import io.renren.common.page.PageData;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.bonus.dao.BonusProcessDao;
import io.renren.modules.bonus.excel.BonusProcessExcel;
import io.renren.modules.bonus.service.BonusListService;
import io.renren.modules.bonus.vo.BonusListVO;
import io.renren.modules.bonus.vo.BonusProcessVO;
import io.renren.modules.bonus.dto.BonusProcessDTO;
import io.renren.modules.bonus.entity.BonusProcessEntity;
import io.renren.modules.bonus.service.BonusProcessService;
import io.renren.modules.bonus.vo.BonusTypeVO;
import io.renren.modules.classinfo.service.ClassInfoService;
import io.renren.modules.classinfo.service.ClassStuRealationService;
import io.renren.modules.classinfo.service.StuInfoService;
import io.renren.modules.classinfo.vo.ClassInfoVO;
import io.renren.modules.classinfo.vo.ClassStuRealationVO;
import io.renren.modules.classinfo.vo.StuInfoVO;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.SysRoleDTO;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysRoleUserService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 奖金申请审核管理
 *
 * @author test test
 * @since 1.0.0 2024-09-11
 */
@Service
public class BonusProcessServiceImpl extends CrudServiceImpl<BonusProcessDao, BonusProcessEntity, BonusProcessVO> implements BonusProcessService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ClassInfoService classInfoService;

    @Autowired
    private StuInfoService stuInfoService;

    @Autowired
    private BonusListService bonusListService;

    @Autowired
    private ClassStuRealationService classStuRealationService;

    @Override
    public QueryWrapper<BonusProcessEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String bonusListId = (String)params.get("bonusListId");
        String userId = (String)params.get("userId");
        String studentIdList = (String)params.get("studentIdList");

        QueryWrapper<BonusProcessEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(bonusListId), "bonus_list_id", bonusListId);
        wrapper.eq(StringUtils.isNotBlank(userId), "user_id", userId);
        if (StringUtils.isNotBlank(studentIdList)) {
            wrapper.in("user_id", studentIdList.split(","));
        }
        return wrapper;
    }

    @Override
    public void save(BonusProcessDTO bonusProcessDTO) {
        BonusProcessEntity bonusProcessEntity = ConvertUtils.sourceToTarget(bonusProcessDTO, BonusProcessEntity.class);
        this.insert(bonusProcessEntity);
    }

    @Override
    public void update(BonusProcessDTO bonusProcessDTO) {
        BonusProcessEntity bonusProcessEntity = ConvertUtils.sourceToTarget(bonusProcessDTO, BonusProcessEntity.class);
        this.updateById(bonusProcessEntity);
    }

    @Override
    public PageData<BonusProcessVO> bonusprocessPage(Map<String, Object> params) {
        Long userId = SecurityUser.getUserId();
        // 判断是否学生
        SysRoleDTO studentRole = sysRoleService.getRole("student");
        List<Long> studentUserIdList = sysRoleUserService.getUserIdList(studentRole.getId());
        if (CollectionUtils.isNotEmpty(studentUserIdList) && studentUserIdList.contains(userId)) {
            params.put("studentIdList", StringUtils.join(Arrays.asList(userId), ","));
        }
        // 判断是否老师
        SysRoleDTO teacherRole = sysRoleService.getRole("teacher");
        List<Long> teacherUserIdList = sysRoleUserService.getUserIdList(teacherRole.getId());
        if (CollectionUtils.isNotEmpty(teacherUserIdList) && teacherUserIdList.contains(userId)) {
            ClassInfoVO classInfoVo = classInfoService.getByTeacherId(userId);
            if (classInfoVo == null) {
                throw new RenException("老师您还未绑定班级！无法查看班级审核信息！");
            }
            List<ClassStuRealationVO> classStuRealationVoList = classStuRealationService.queryByClassInfoId(classInfoVo.getId());
            params.put("studentIdList", classStuRealationVoList.stream().map(e -> e.getStudentId().toString()).distinct().collect(Collectors.joining(",")));
        }

        List<SysUserDTO> userDtoList = sysUserService.getAll();
        List<BonusListVO> bonusListVoList = bonusListService.getAll();
        PageData<BonusProcessVO> page = this.page(params);
        page.getList().forEach(e -> {
            BonusListVO bonusListVo = bonusListVoList.stream().filter(j -> j.getId().compareTo(e.getBonusListId()) == 0).findAny().orElse(null);
            e.setBonusListVo(bonusListVo);
            SysUserDTO user = userDtoList.stream().filter(j -> j.getId().compareTo(e.getUserId()) == 0).findAny().orElse(null);
            e.setUserName(user == null ? "-" : user.getRealName());
            if (e.getCollegeUserId() != null) {
                SysUserDTO collegeUser = userDtoList.stream().filter(j -> j.getId().compareTo(e.getCollegeUserId()) == 0).findAny().orElse(null);
                e.setCollegeUserName(collegeUser == null ? "-" : collegeUser.getRealName());
            }
            if (e.getDepartmentUserId() != null) {
                SysUserDTO departmentUser = userDtoList.stream().filter(j -> j.getId().compareTo(e.getDepartmentUserId()) == 0).findAny().orElse(null);
                e.setDepartmentUserName(departmentUser == null ? "-" : departmentUser.getRealName());
            }
            SysUserDTO creator = userDtoList.stream().filter(j -> j.getId().compareTo(e.getCreator()) == 0).findAny().orElse(null);
            e.setCreatorName(creator == null ? "-" : creator.getRealName());
            SysUserDTO updater = userDtoList.stream().filter(j -> j.getId().compareTo(e.getUpdater()) == 0).findAny().orElse(null);
            e.setUpdaterName(updater == null ? "-" : updater.getRealName());
        });
        return page;
    }

    @Override
    public void collegeApproved(BonusProcessDTO dto) {
        Long userId = SecurityUser.getUserId();
        // 判断是否学院
        SysRoleDTO collegeRole = sysRoleService.getRole("college");
        List<Long> collegeUserIdList = sysRoleUserService.getUserIdList(collegeRole.getId());
        if (CollectionUtils.isNotEmpty(collegeUserIdList) && collegeUserIdList.contains(userId)) {
            BonusProcessEntity entity = this.baseDao.selectById(dto.getId());
            if (entity.getCollegeStatus() != 0) {
                throw new RenException("已审核！请勿重复操作！");
            }
            dto.setCollegeUserId(SecurityUser.getUserId());
            this.update(dto);
        } else {
            throw new RenException("您不是学院！无法审核！");
        }
    }

    @Override
    public void departmentApproved(BonusProcessDTO dto) {
        Long userId = SecurityUser.getUserId();
        // 判断是否学校部门
        SysRoleDTO departmentRole = sysRoleService.getRole("department");
        List<Long> departmentUserIdList = sysRoleUserService.getUserIdList(departmentRole.getId());
        if (CollectionUtils.isNotEmpty(departmentUserIdList) && departmentUserIdList.contains(userId)) {
            BonusProcessEntity entity = this.baseDao.selectById(dto.getId());
            if (entity.getCollegeStatus() == 0) {
                throw new RenException("学院还未审核！请等待学院审核完成！");
            }
            if (entity.getDepartmentStatus() != 0) {
                throw new RenException("已审核！请勿重复操作！");
            }
            dto.setDepartmentUserId(SecurityUser.getUserId());
            this.update(dto);
        } else {
            throw new RenException("您不是学校部门！无法审核！");
        }
    }

    @Override
    public void bonusApplication(BonusProcessDTO dto) {
        // 获取当前时间
        Date currentDate = new Date();
        BonusListVO bonusListVo = bonusListService.get(dto.getBonusListId());
        if (bonusListVo.getStartDate().after(currentDate)) {
            throw new RenException("该奖金的申请时间还未开始！");
        }
        if (bonusListVo.getEndDate().before(currentDate)) {
            throw new RenException("该奖金的申请时间已结束！");
        }
        // 申请人
        dto.setUserId(SecurityUser.getUserId());

        StuInfoVO stuInfoVo = stuInfoService.getByStudentId(SecurityUser.getUserId());
        if (stuInfoVo == null) {
            throw new RenException("您还未绑定学生信息，无法申请奖金！");
        }
        if (bonusListVo.getMinGpa() != null && stuInfoVo.getGpa().compareTo(bonusListVo.getMinGpa()) < 0) {
            throw new RenException("您的绩点不符合申请条件！");
        }
        if (bonusListVo.getMinTestingScore() != null && stuInfoVo.getTestingScore().compareTo(bonusListVo.getMinTestingScore()) < 0) {
            throw new RenException("您的综测分不符合申请条件！");
        }
        if (bonusListVo.getMinDifficultyLevel() != null && stuInfoVo.getDifficultyLevel().compareTo(bonusListVo.getMinDifficultyLevel()) < 0) {
            throw new RenException("您的困难等级不符合申请条件！");
        }


        this.save(dto);
    }

    @Override
    public List<BonusProcessExcel> exportList(Map<String, Object> params) {
        Long userId = SecurityUser.getUserId();
        // 判断是否学生
        SysRoleDTO studentRole = sysRoleService.getRole("student");
        List<Long> studentUserIdList = sysRoleUserService.getUserIdList(studentRole.getId());
        if (CollectionUtils.isNotEmpty(studentUserIdList) && studentUserIdList.contains(userId)) {
            params.put("studentIdList", StringUtils.join(Arrays.asList(userId), ","));
        }
        // 判断是否老师
        SysRoleDTO teacherRole = sysRoleService.getRole("teacher");
        List<Long> teacherUserIdList = sysRoleUserService.getUserIdList(teacherRole.getId());
        if (CollectionUtils.isNotEmpty(teacherUserIdList) && teacherUserIdList.contains(userId)) {
            ClassInfoVO classInfoVo = classInfoService.getByTeacherId(userId);
            if (classInfoVo == null) {
                throw new RenException("老师您还未绑定班级！无法查看班级审核信息！");
            }
            List<ClassStuRealationVO> classStuRealationVoList = classStuRealationService.queryByClassInfoId(classInfoVo.getId());
            params.put("studentIdList", classStuRealationVoList.stream().map(e -> e.getStudentId().toString()).distinct().collect(Collectors.joining(",")));
        }

        List<SysUserDTO> userDtoList = sysUserService.getAll();
        List<BonusListVO> bonusListVoList = bonusListService.getAll();
        List<BonusProcessEntity> processEntityList = this.baseDao.selectList(getWrapper(params));

        List<BonusProcessExcel> excelList = new ArrayList<>();
        processEntityList.forEach(e -> {
            BonusProcessExcel excel = new BonusProcessExcel();

            BonusListVO bonusListVo = bonusListVoList.stream().filter(j -> j.getId().compareTo(e.getBonusListId()) == 0).findAny().orElse(null);
            excel.setTitle(bonusListVo == null ? "-" : bonusListVo.getTitle());
            excel.setBonusTypeName(bonusListVo == null ? "-" : bonusListVo.getBonusTypeName());
            excel.setMoney(bonusListVo == null ? new BigDecimal("0") : bonusListVo.getMoney());
            SysUserDTO user = userDtoList.stream().filter(j -> j.getId().compareTo(e.getUserId()) == 0).findAny().orElse(null);
            excel.setUserName(user == null ? "-" : user.getRealName());
            if (e.getCollegeUserId() != null) {
                SysUserDTO collegeUser = userDtoList.stream().filter(j -> j.getId().compareTo(e.getCollegeUserId()) == 0).findAny().orElse(null);
                excel.setCollegeUserName(collegeUser == null ? "-" : collegeUser.getRealName());
            }
            excel.setCollegeStatusName(e.getCollegeStatus() == 0 ? "待审核" : e.getCollegeStatus() == 1 ? "审核通过" : "审核未通过");
            if (e.getDepartmentUserId() != null) {
                SysUserDTO departmentUser = userDtoList.stream().filter(j -> j.getId().compareTo(e.getDepartmentUserId()) == 0).findAny().orElse(null);
                excel.setDepartmentUserName(departmentUser == null ? "-" : departmentUser.getRealName());
            }
            excel.setDepartmentStatusName(e.getDepartmentStatus() == 0 ? "待审核" : e.getDepartmentStatus() == 1 ? "审核通过" : "审核未通过");
            excel.setCreateDate(e.getCreateDate());
            excelList.add(excel);
        });
        return excelList;
    }

}